package com.gome.boot.common.util;

import java.security.MessageDigest;

/**
 * 加解密工具类.
 *
 * @author baoxiufeng
 */
public class CryptUtils {
    /**
     * 十六进制有效值列表
     */
    private static final String[] HEX_DIGITS = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    /**
     * MD5加密.
     *
     * @param s 待加密字符串
     * @return 加密后的MD5串
     */
    public static String md5(String s) {
        if (s != null) {
            try {
                return byteArrayToHexString(MessageDigest.getInstance("MD5").digest(s.getBytes()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private static String byteArrayToHexString(byte[] b) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < b.length; ++i) {
            sb.append(byteToHexString(b[i]));
        }
        return sb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b < 0 ? (256 + b) : b;
        return HEX_DIGITS[n / 16] + HEX_DIGITS[n % 16];
    }
}
